package top.songxs.controller;

import com.alibaba.dubbo.config.annotation.Reference;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import top.songxs.base.BaseController;
import top.songxs.entity.Permission;
import top.songxs.service.PermissionService;

import java.util.List;

@Controller
@RequestMapping("/permission")
public class PermissionController extends BaseController {
    private static final String PAGE_INDEX = "permission/index";
    private static final String PAGE_CREATE = "permission/create";
    private static final String LIST_ACTION = "redirect:/permission";
    private static final String PAGE_EDIT = "permission/edit";
    private static final String PAGE_SUCCESS = "common/successPage";

    @Reference
    private PermissionService permissionService;

    //使得前端请求跳转到指定页面
    @RequestMapping
    public String index(Model model) {
        //调用业务层的方法，查询所有菜单并构建父子级菜单结构并返回
        List<Permission> permissionList = permissionService.findAllMenu();
        //存储到请求域中
        model.addAttribute("list", permissionList);
        return PAGE_INDEX;
    }

    @GetMapping("/create")
    public String create(Permission permission, Model model
    ) {
        model.addAttribute("permission", permission);
        return PAGE_CREATE;
    }

    @PostMapping("/save")
    public String save(Permission permission, Model model) {
        permissionService.insert(permission);
        return successPage(model, "新增菜单成功");
    }

    /**
     * 编辑
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/edit/{id}")
    public String edit(ModelMap model, @PathVariable Long id) {
        Permission permission = permissionService.getById(id);
        model.addAttribute("permission", permission);
        return PAGE_EDIT;
    }

    @PostMapping(value = "/update")
    public String update(Permission permission) {
        permissionService.update(permission);
        return PAGE_SUCCESS;
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Long id) {
        //调用业务层的方法 根据id删除菜单
        permissionService.delete(id);
        //删除成功之后重新删除菜单首页
        return LIST_ACTION;

    }

}
